//
//  FFObject.cpp
//  ForceField
//
//  Created by Roxanne Brittain on 11/15/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#include <iostream>
#import "FFObject.h"
#import "FFUtilities.h"

void FFObject::randomizeValues(float w, float h)
{
    setVelocity([FFUtilities randomNumberFrom:-200 to:200], [FFUtilities randomNumberFrom:-200 to:200]);
    m_radius = [FFUtilities randomNumberFrom:5 to:80];
    m_mass = .001*M_PI*m_radius*m_radius;
    setSize(m_radius*2, m_radius*2);
    float xPosition = [FFUtilities randomNumberUpTo:w-2*m_radius];
    float yPosition = [FFUtilities randomNumberUpTo:h-2*m_radius];
    setPosition(xPosition, yPosition);
}

void FFObject::checkBoundaries(float x, float y, float w, float h)
{
    bool changed = false;
    if (m_xPosition <= x) {
        if (m_xVelocity<0) {
            m_xVelocity = fabs(m_xVelocity);
            m_xVelocity *= .8;
            changed = true;
        }
    }
    if (m_yPosition <= y) {
        if (m_yVelocity<0) {
            m_yVelocity = fabs(m_yVelocity);
            m_yVelocity *= .8;
            changed = true;
        }
    }
    if (m_xPosition+getWidth() >= (x+w)) {
        if (m_xVelocity>0) {
            m_xVelocity = -1 * fabs(m_xVelocity);
            m_xVelocity *= .8;
            changed = true;
        }
    }
    if (m_yPosition+getHeight() >= (y+h)) {
        if (m_yVelocity>0) {
            m_yVelocity = -1 * fabs(m_yVelocity);
            m_yVelocity *= .8;
            changed = true;
        }
    }
    
}

void FFObject::updateAcceleration()
{
    std::vector<FFVector*>::iterator it;
    
    m_xAcceleration = m_yAcceleration = 0;
    for (it=forceVector.begin(); it < forceVector.end(); it++ )
    {
        FFVector *force = *it;
        
        m_xAcceleration += force->getX()/m_mass;
        m_yAcceleration += force->getY()/m_mass;
    }
    
}

void FFObject::updateVelocityWithSeconds(float s)
{
    m_xVelocity += m_xAcceleration * s;
    m_yVelocity += m_yAcceleration * s;
}

void FFObject::updatePositionWithSeconds(float s)
{
    m_xPosition += m_xVelocity * s;
    m_yPosition += m_yVelocity * s;
//    NSLog(@"acc: %.02f %.02f", m_xAcceleration, m_yAcceleration);
//    NSLog(@"vel: %.02f %.02f", m_xVelocity, m_yVelocity);
//    NSLog(@"pos: %.02f %.02f", m_xPosition, m_yPosition);
}